// 导入数据库操作模块
const { mysql } = require("../../db");
const { filesURL } = require("../../../config");
const bcrypt = require("bcryptjs");
const moment = require("moment");

const formatData = (results) => {
	try {
		const data = results.map(({ username, password, ...o }) => ({
			...o,
			register: moment(o.register).format("YYYY-MM-DD HH:mm:ss"),
			avatar: o.avatar ? `${filesURL}/images/avatar/${o.avatar}` : null
		}));
		return data;
	} catch (err) {
		throw err;
	}
};

// 获取所有用户信息
exports.Info = async (req, res, table) => {
	try {
		const sqlStr = `SELECT * FROM ${table} WHERE roles != 'SuperAdmin'`;
		const [results] = await mysql.query(sqlStr);
		if (results.length === 0) return res.error("暂无用户信息!");
		const data = formatData(results);
		return res.success(data);
	} catch (err) {
		return res.error(err);
	}
};

// 新增管理员
exports.Add = async (req, res, table) => {
	try {
		const { username, password, email, code } = req.body;
		const sqlStr1 = `SELECT * FROM ${table} WHERE username = ? OR email = ?`;
		const [results1] = await mysql.query(sqlStr1, [username, email]);
		if (results1.length > 0) return res.error("用户名或邮箱已存在！");

		const data = { username, password: bcrypt.hashSync(password, 10), email, code, roles: "Admin" };
		const sqlStr2 = "INSERT INTO userinfo SET ?";
		const [results2] = await mysql.query(sqlStr2, data);
		if (results2.affectedRows !== 1) return res.error("新增失败！");
		return res.success("新增成功！");
	} catch (err) {
		return res.error(err);
	}
};

exports.Search = async (req, res, table) => {
	const info = req.params.value;

	try {
		const sqlStr = `SELECT * FROM ${table} WHERE (nickname LIKE ? OR email LIKE ? OR roles LIKE ? OR gender LIKE ? OR age LIKE ? OR is_talk LIKE ? OR is_delete LIKE ?) AND roles != "SuperAdmin"`;
		const SeletePattern = `%${info}%`;
		const values = Array(7).fill(SeletePattern);
		const [results] = await mysql.query(sqlStr, values);
		if (results.length === 0) return res.error("该用户不存在");
		const data = formatData(results);
		return res.success(data);
	} catch (err) {
		return res.error(err);
	}
};